---
title: Structs
sidebar_position: 4
description: Introduction to Mojo structures (structs).
---

A Mojo struct is a data structure that allows you to encapsulate fields and
methods that operate on an abstraction, such as a data type or an object.
**Fields** are variables that hold data relevant to the struct, and **methods**
are functions inside a struct that generally act upon the field data.

For example, if you're building a graphics program, you can use a struct to
define an `Image` that has fields to store information about each image
(such as the pixels) and methods that perform actions on it (such as rotate
it).

For the most part, Mojo's struct format is designed to provide a static,
memory-safe data structure for high-level data types used in programs. For
example, all the data types in Mojo's standard library (such as `Int`,
`Bool`, `String`, and `Tuple`) are defined as structs.

If you understand how [functions](/mojo/manual/functions) and
[variables](/mojo/manual/variables) work in Mojo, you probably
noticed that Mojo is designed to provide dynamic programming features in a
`def` function while enforcing stronger code safety in `fn` functions. When it
comes to structs, Mojo leans toward the safe side: You can still choose whether
to use either `def` or `fn` declarations for methods, but all fields must be
declared with `var`.

## Struct definition

You can define a simple struct called `MyPair` with two fields like this:

```mojo
struct MyPair:
    var first: Int
    var second: Int
```

However, you can't instantiate this struct because it has no constructor
method. So here it is with a constructor to initialize the two fields:

```mojo
struct MyPair:
    var first: Int
    var second: Int

    fn __init__(out self, first: Int, second: Int):
        self.first = first
        self.second = second
```

Notice that the first argument in the `__init__()` method is `out self`. You'll
have a `self` argument as the first argument on all struct methods. It
references the current struct instance (it allows code in the method to refer to
"itself"). *When you call the constructor, you never pass a value for
`self`—Mojo passes it in automatically.*

The `out` portion of `out self` is an [argument
convention](/mojo/manual/values/ownership#argument-conventions) that declares
`self` as a mutable reference that starts out as uninitialized and must be
initialized before the function returns.

Many types use a field-wise constructor like the one shown for `MyPair` above:
it takes an argument for each field, and initializes the fields directly from
the arguments.  To save typing, Mojo provides a
[`@fieldwise_init`](/mojo/manual/decorators/fieldwise-init) decorator, which
generates a field-wise constructor for the struct. So you can rewrite the
`MyPair` example above like this:

```mojo
@fieldwise_init
struct MyPair:
    var first: Int
    var second: Int
```

The `__init__()` method is one of many [special methods](#special-methods)
(also known as "dunder methods" because they have *d*ouble *under*scores) with
pre-determined names.

:::note

You can't assign values when you declare fields. You must initialize
all of the struct's fields in the constructor. (If you try to leave a field
uninitialized, the code won't compile.)

:::

## Constructing a struct type

Once you have a constructor, with `__init__` or using `@fieldwise_init`,
you can create an instance of `MyPair` and set the fields:

```mojo title="Construct an instance"
var mine = MyPair(2, 4)
print(mine.first)
```

```output
2
```

Initializer lists make it simple to construct instances without spelling out the type name.
For example, here's the standard way to call a function:

```mojo title="Calling a function"
def process_pair(pair: MyPair):
    ...

process_pair(MyPair(2, 4))
```

Because `process_pair` expects a `MyPair` instance, Mojo infers that
from context. Use braces to construct the instance with an initializer
list:

```mojo title="Using an initializer list"
process_pair({2, 4})
```

Initializer lists support all Mojo argument styles, including keyword
arguments. For example:

```mojo title="Initializer lists with a keyword argument"
def utility_function(argument: CustomType):
    ...

utility_function(CustomType(0.5, fish="swordfish"))

...is equivalent to...

utility_function({0.5, fish="swordfish"})
```

The result is concise, and both calls are functionally identical in the
preceding example.

You can also update declared instances with initializer lists.
Mojo knows the variable's type. For example:

```mojo title="Reassignment with initializer lists"
# Construct a new instance
myCustomType = CustomType(0.5, fish="swordfish")

# Use the instance
...

# Update the instance before further use
myCustomType = {0.7, fish="salmon"}
```

## Making a struct Copyable {#making-a-struct-copyable-and-movable}

Mojo structs are not copyable or movable by default.

For example, the following code produces errors:

```mojo
var a = MyPair(1, 2)

# Implicit copy
var b = a  # value of type 'MyPair' is not implicitly copyable, it does not
           # conform to 'ImplicitlyCopyable'

# Explicit copy
var c = a.copy()  # 'MyPair' value has no attribute 'copy'

# Move
var d = a^  #  value of type 'MyPair' cannot be copied or moved; consider
            # conforming it to 'Copyable', which also adds 'Movable' conformance.

```

In most cases, you can make a struct copyable (and movable) just by adding the
`Copyable` [trait](/mojo/manual/traits).

### Movability

To make a struct move-only, add the `Movable` trait:

  ```mojo
  struct MyPair(Movable):
  ...
  ```

Mojo will generate a move constructor for you. You have rarely need to
write your own custom move constructor. For more information,
see the section on
[move constructors](/mojo/manual/lifecycle/life#move-constructor).

### Copyability

To make a struct copyable, add the `Copyable` trait:

  ```mojo
  struct MyPair(Copyable):
    ...
  ```

In most cases, that's all you need to do. Mojo will generate a copy constructor
( `__copyinit__()` method) for you. You don't need to write your own unless you
need custom logic in the copy constructor—for example, if your struct
dynamically allocates memory. For more information, see the section on
[copy constructors](/mojo/manual/lifecycle/life#copy-constructor).

The `Copyable` trait supplies the `copy()` method, which
provides a more user-friendly way to copy a value than invoking the
copy constructor directly.

In addition, `Copyable` automatically adds movability, so you won't
need to add both `Copyable` _and_ `Movable` to your declarations.

### Implicit copyability

To make a struct implicitly copyable, add the `ImplicitlyCopyable` trait:

```mojo
struct MyPair(ImplicitlyCopyable):
    ...
```

`ImplicitlyCopyable` automatically implies `Copyable` and `Movable`, so all
the notes related to copyability apply here. A type should only be implicitly
copyable if copying the type is inexpensive and has no side effects. Unnecessary
copies can be a big drain on memory and performance, so use this trait with
caution.

## Methods

In addition to special methods like `__init__()`, you can add any other method
you want to your struct. For example:

```mojo
@fieldwise_init
struct MyPair:
    var first: Int
    var second: Int

    fn get_sum(self) -> Int:
        return self.first + self.second
```

```mojo
var mine = MyPair(6, 8)
print(mine.get_sum())
```

```output
14
```

Notice that `get_sum()` also uses the `self` argument, because this is
the only way you can access the struct's fields in a method. The name `self` is
just a convention, and you can use any name you want to refer to the struct
instance that is always passed as the first argument.

Methods that take the implicit `self` argument are called *instance methods*
because they act on an instance of the struct.

:::note

The `self` argument in a struct method is the only argument in an
`fn` function that does not require a type. You can include it if you want, but
you can elide it because Mojo already knows its type (`MyPair` in this case).

:::

### `fn` versus `def` in struct methods

Struct methods can be declared with either the `def` or `fn` keywords. One
important difference is that an `fn` function without the `raises` keyword can't
raise an error. When you call a function that *can* raise an error from inside a
method that *can't* raise an error, Mojo requires you to handle any errors, as
described in
[Errors, error handling, and context managers](/mojo/manual/errors).

If you're writing code that you expect to use widely or distribute as a package,
you may want to use `fn` functions for APIs that can't raise an error to limit
the number of places users need to add error handling code.

A struct's `__del__()` method, or destructor, **must** be a non-raising method,
so it's always declared with `fn` (and without the `raises` keyword).

### Static methods

A struct can also have *static methods*. A static method can be called without
creating an instance of the struct. Unlike instance methods, a static method
doesn't receive the implicit `self` argument, so it can't access any fields on
the struct.

To declare a static method, use the `@staticmethod` decorator and don't include
a `self` argument:

```mojo
struct Logger:

    fn __init__(out self):
        pass

    @staticmethod
    fn log_info(message: String):
        print("Info: ", message)
```

You can invoke a static method by calling it on the type (in this case,
`Logger`). You can also call it on an instance of the type. Both forms are
shown below:

```mojo
Logger.log_info("Static method called.")
var l = Logger()
l.log_info("Static method called from instance.")
```

```output
Info:  Static method called.
Info:  Static method called from instance.
```

## Structs compared to classes

If you're familiar with other object-oriented languages, then structs might
sound a lot like classes, and there are some similarities, but also some
important differences. Eventually, Mojo will also support classes to match the
behavior of Python classes.

So, let's compare Mojo structs to Python classes. They both support methods,
fields, operator overloading, decorators for metaprogramming, and more, but
their key differences are as follows:

* Python classes are dynamic: they allow for dynamic dispatch, monkey-patching
  (or “swizzling”), and dynamically binding instance fields at runtime.

* Mojo structs are static: they are bound at compile-time (you cannot add
  methods at runtime). Structs allow you to trade flexibility for performance
  while being safe and easy to use.

* Mojo structs do not support inheritance ("sub-classing"), but a struct can
  implement [traits](/mojo/manual/traits).

* Python classes support class attributes—values that are shared by all
  instances of the class, equivalent to class variables or static data members
  in other languages.

* Mojo structs don't support static data members.

Syntactically, the biggest difference compared to a Python class is that all
fields in a struct must be explicitly declared with `var`.

In Mojo, the structure and contents of a struct are set at compile time and
can't be changed while the program is running. Unlike in Python, where you can
add, remove, or change attributes of an object on the fly, Mojo doesn't allow
that for structs.

However, the static nature of structs helps Mojo run your code faster. The
program knows exactly where to find the struct's information and how to use it
without any extra steps or delays at runtime.

Mojo's structs also work really well with features you might already know from
Python, like operator overloading (which lets you change how math symbols like
`+` and `-` work with your own data, using [special
methods](#special-methods)).

As mentioned above, all Mojo's standard types
(`Int`, `String`, etc.) are made using structs, rather than being hardwired
into the language itself. This gives you more flexibility and control when
writing your code, and it means you can define your own types with all the same
capabilities (there's no special treatment for the standard library types).

## Special methods

Special methods (or "dunder methods") such as `__init__()` are pre-determined
method names that you can define in a struct to perform a special task.

Although it's possible to call special methods with their method names, the
point is that you never should, because Mojo automatically invokes them in
circumstances where they're needed (which is why they're also called "magic
methods"). For example, Mojo calls the `__init__()` method when you create
an instance of the struct; and when Mojo destroys the instance, it calls the
`__del__()` method (if it exists).

Even operator behaviors that appear built-in (`+`, `<`, `==`, `|`, and so on)
are implemented as special methods that Mojo implicitly calls upon to perform
operations or comparisons on the type that the operator is applied to.

Mojo supports a long list of special methods; far too many to discuss here, but
they generally match all of [Python's special
methods](https://docs.python.org/3/reference/datamodel#special-method-names)
and they usually accomplish one of two types of tasks:

* Operator overloading: A lot of special methods are designed to overload
  operators such as `<` (less-than), `+` (add), and `|` (or) so they work
  appropriately with each type. For more information, see
  [Implement operators for custom types](/mojo/manual/operators#implement-operators-for-custom-types).

* Lifecycle event handling: These special methods deal with the lifecycle and
  value ownership of an instance. For example, `__init__()` and `__del__()`
  demarcate the beginning and end of an instance lifetime, and other special
  methods define the behavior for other lifecycle events such as how to copy or
  move a value.

You can learn all about the lifecycle special methods in the [Value
lifecycle](/mojo/manual/lifecycle/) section. However, most structs are simple
aggregations of other types, so unless your type requires custom behaviors when
an instance is created, copied, moved, or destroyed, you can synthesize the
essential lifecycle methods you need (and save yourself some time) using the
`@fieldwise_init` decorator (described in
[Struct definition](#struct-definition)), and the `Copyable` and `Movable`
traits (described in
[Making a struct copyable](#making-a-struct-copyable-and-movable)).
